#!/bin/bash
## ---------------------------------------------------------------------
##
## Copyright (C) 2018 by the deal.II authors
##
## This file is part of the deal.II library.
##
## The deal.II library is free software; you can use it, redistribute
## it, and/or modify it under the terms of the GNU Lesser General
## Public License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
## The full text of the license can be found in the file LICENSE.md at
## the top level directory of deal.II.
##
## ---------------------------------------------------------------------
set -eu

BASE_URL="https://cdash.kyomu.43-1.org/"

# Quick and dirty script to query CDash on the command line and create a
# formatted table

links=false
regex="commit"

print_help() {
  echo "Usage: query_testsuite [-c|--commit <commit>] [-l|--links] [-h|--help]"
  echo ""
  echo "Queries the CDash on the command line and creates a formatted table"
  echo "compatible with markdown"
  echo ""
  echo "Options:"
  echo "  -r (--regex)   : only show results for hosts/commits matching the specified regex"
  echo "  -l (--links)   : include hyperlinks"
  echo "  -h (--help)    : print this help message"
}

until [[ "$*" == "" ]]; do
  if  [[ "$1" == -h || "$1" == --help ]]; then
    print_help
    exit 1
  elif  [[ "$1" == -l || "$1" == --links ]]; then
    links=true
  elif  [[ "$1" == -r || "$1" == --regex ]]; then
    shift
    regex="$1"
  else
    print_help
    exit 1
  fi
  shift
done

query_testsuite() {
  (echo "| Host | Configuration | Commit | Build errors | Build warnings | Failing tests | Passing tests | |";
  echo -n "| - | - | - | :-: | :-: | :-: | :-:";
  curl -s "${BASE_URL}/index.php?project=deal.II" |
  grep -P -B 10 -A 43 "${regex}" |
  grep -P "(only(failed|passed)|BuildError|commit|platform|site)" |
  grep -v "onlydelta" |
  sed -e "s#<a href=\"\\(view.*\\)\">\\([0-9]*\\)</a>#[\\2](${BASE_URL}\\1)#" \
      -e "s#<a href=\".*\\(https://github.com/.*\\)\">\\(.*\\)&nbsp;</a>#[\\2](\\1)#" \
      -e "s#.*\\(buildSummary.php?buildid=[0-9]*\\)\"[^>]*>\\([^<]*\\).*#[\\2](${BASE_URL}\\1)#" \
      -e 's#</a>##g' \
      -e 's#.*>##g' |
  awk '{printf (NR%7==1) ? " |\n| " $0 : " | " $0}' |
  sed -e "s#\\(.*buildid=\\([0-9]*\\).*\\)#\\2 \\1#" |
  sort -n -k 1 |
  sed -e "s#[0-9 ]*\\(.*\\)#\\1#" |
  if $links; then
      cat
  else
      sed -e 's#\[\([^]]*\)\]([^)]*)#\1#g'
  fi) |
  sed -e 's#\[\(0*\)\]([^)]*)#\1#g' \
      -e 's#\[\([^]]*\)\]([^)]*onlypassed[^)]*)#\1#g' \
      -e 's#\[\([0-9]*\)\]#[<b>\1</b>]#g' \
      -e 's#[ ]\+# #g' |
  column -t --separator "|" --output-separator " | "
}

query_testsuite
